﻿using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Physics;
using Unity.Physics.Systems;
using Unity.Transforms;

namespace MyTanks
{
    [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
    [UpdateBefore(typeof(PhysicsSimulationGroup))]
    public partial struct CollisionResultSystem : ISystem
    {
        [BurstCompile]
        public partial struct ShellHitTarget : ICollisionEventsJob
        {
            public ComponentLookup<Shell> ShellData;
            public EntityCommandBuffer ecb;
            public BufferLookup<ShellExplosionBufferComponent> shellExplosionBuffer;
            public void Execute(CollisionEvent collisionEvent)
            {
                Entity entityA = collisionEvent.EntityA;
                Entity entityB = collisionEvent.EntityB;

                bool isBodyAShell = ShellData.HasComponent(entityA);
                bool isBodyBShell = ShellData.HasComponent(entityB);

                if (isBodyAShell)
                {
                    World.DefaultGameObjectInjectionWorld.EntityManager.SetComponentEnabled<ShellIsIdle>(entityA, true);
                }

                if (isBodyBShell)
                {
                    World.DefaultGameObjectInjectionWorld.EntityManager.SetComponentEnabled<ShellIsIdle>(entityB, true);
                }
            }
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var shellsHolder = SystemAPI.GetSingletonEntity<ShellHolder>();
            var shellExplosionBuffer = SystemAPI.GetBuffer<ShellExplosionBufferComponent>(shellsHolder);


            state.Dependency = new ShellHitTarget
            {
                ecb = new EntityCommandBuffer(Allocator.TempJob),
                explosionBuffer = shellExplosionBuffer,
                ShellData = SystemAPI.GetComponentLookup<Shell>()
            }.Schedule(SystemAPI.GetSingleton<SimulationSingleton>(), state.Dependency);
        }
    }
}